package com.bingo.generate.comm.util.bean;

import com.baomidou.mybatisplus.annotation.TableField;
import com.bingo.generate.comm.util.StringHelper;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.reflect.FieldUtils;

import java.lang.reflect.Field;
import java.security.Key;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


public class SqlBeanUtil {

    public static  <T> T mapToBean(Map<String,Object> map,Class<T> tClass,String... ignore){
        Map<String, Field> fieldMap=new HashMap<>();
        Field[] allFields = FieldUtils.getAllFields(tClass);
        for (Field field : allFields) {
            String fieldName=field.getName();
            String key = StringHelper.camelToUnderline(fieldName);
            key=key.toLowerCase();
            //  判断是否有TableFIeld注解
            TableField tableField=field.getAnnotation(TableField.class);
            if(tableField!=null && StringUtils.isNotEmpty(tableField.value())){
                String val=tableField.value().toLowerCase();
                key=val;
            }
            fieldMap.put(key,field);
        }

        T obj= null;
        try {
            obj = tClass.newInstance();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        final T objectFinal=obj;

        map.forEach((k,V)->{
            //  转换为小写驼峰
            String key = k.toLowerCase();
            key=StringHelper.camelToUnderline(key);
            Field field = fieldMap.get(key);
            if (field==null){
                return;
            }
            try {
                FieldUtils.writeField(field,objectFinal,V,true);
            } catch (Exception e) {
                System.out.println("出现错误数据  错误的mapKey:"+k+"  "+e.getMessage());
            }
        });

        return objectFinal;
    }

}
